package com.atguigu.gulimall.product.service.impl;

import com.atguigu.gulimall.product.service.CategoryBrandRelationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.product.dao.CategoryDao;
import com.atguigu.gulimall.product.entity.CategoryEntity;
import com.atguigu.gulimall.product.service.CategoryService;
import org.springframework.transaction.annotation.Transactional;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Autowired
    CategoryBrandRelationService categoryBrandRelationService;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }


    /**
     * 查询为树形结构
     * 使用链式编程进行编写代码
     * 确实是省时间省力气
     *
     * 先过滤器，过滤结果
     * 然后通过 map 为子菜单设置集合
     * 在排序
     * 最后收集结果
     *
     * @return
     */
    @Override
    public List<CategoryEntity> listWithTree() {
        //查询商品
        List<CategoryEntity> categoryEntities = baseMapper.selectList(null);

        //查出一级分类
        List<CategoryEntity> level1Menus = categoryEntities.stream().filter(categoryEntity -> {
            return categoryEntity.getParentCid() == 0;
        }).map(menu->{
            menu.setChildren(getChildrens(menu,categoryEntities));
            return menu;
        }).sorted((menu1,menu2)->{
            return menu1.getSort()-menu2.getSort();
        }).collect(Collectors.toList());
        //组装为树形结构
        return level1Menus;
    }

    @Override
    public void removeMenuByIds(List<Long> list) {
        //TODO   检查当前删除的菜单是否被别的地方引用
        baseMapper.deleteBatchIds(list);
    }

    @Override
    public Long[] findCateLogPath(Long catelogId) {
        List<Long> paths = new ArrayList<>();

        List<Long> parentPath = findParentPath(catelogId, paths);
        Collections.reverse(parentPath);
        //把收集到的集合转换为数组
        return  parentPath.toArray(new Long[parentPath.size()]);
    }

    @Transactional//开启事务的注解
    @Override
    public void updateCascade(CategoryEntity category) {
        this.updateById(category);
        categoryBrandRelationService.updateCategory(category.getCatId(), category.getName());
    }

    /**
     * 递归查找数据
     * 先把当前路径添加进去
     *    然后获取category实体信息
     *  最后根据category实体信息的ParentCid是否为0 继续递归调用
     */
    private List<Long> findParentPath(Long catelogId, List<Long> path) {
        path.add(catelogId);
        CategoryEntity byId = this.getById(catelogId);
        if (byId.getParentCid() != 0) {
            findParentPath(byId.getParentCid(),path);
        }
        return path;
    }

    /**
     * 这个方法用于子菜单的分类
     * //递归过滤子菜单
     *
     * 链式编程，
     * 先过滤条件
     * 在通过map设置子菜单
     * 再排序
     * 最后收集结果
     *
     */
    private List<CategoryEntity> getChildrens(CategoryEntity root,List<CategoryEntity> all){
        List<CategoryEntity> collectChildren = all.stream().filter(categoryEntity -> {
            return categoryEntity.getParentCid() == root.getCatId();
        }).map(categoryEntity->{
            categoryEntity.setChildren(getChildrens(categoryEntity,all));
            return categoryEntity;
        }).sorted((menu1,menu2)->{
            return  (menu1.getSort()==null?0:menu1.getSort())-(menu2.getSort()==null?0:menu2.getSort());
        }).collect(Collectors.toList());

        return  collectChildren;
    }

}